package com.imau.common.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTypeHandler implements TypeHandler<Date> {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public void setParameter(PreparedStatement ps, int i, Date date, JdbcType jdbcType) throws SQLException {
        if (date == null) {
            ps.setNull(i, jdbcType.TYPE_CODE);
        } else {
            ps.setString(i, sdf.format(date));
        }
    }

    @Override
    public Date getResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp ts = rs.getTimestamp(columnName);
        return ts == null ? null : new Date(ts.getTime());
    }

    @Override
    public Date getResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp ts = rs.getTimestamp(columnIndex);
        return ts == null ? null : new Date(ts.getTime());
    }

    @Override
    public Date getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp ts = cs.getTimestamp(columnIndex);
        return ts == null ? null : new Date(ts.getTime());
    }
}

